from concurrent.futures import ThreadPoolExecutor, as_completed

from PySide2.QtCore import QThread, Signal
from api.api_project import get_token_to_public_data, get_file_to_db
from common.config import Public_Data
from common.pd import DF_Table

# from time import sleep
# from random import  randint

from common.utils import get_now_str


class Th_Update_file(QThread):
    child_signal = Signal(str)

    def run(self):
        self.get_file_json_tb_db_pool()

    def get_file_json_tb_db_pool(self, contract_list=None):
        public_data = Public_Data()
        if not contract_list:
            df_contract = public_data.Df_Contract
            if df_contract.empty:  # 检查是否有合同信息
                self.child_signal.emit("无合同信息")
                return
            # period = __get_period()  # 获取需要更新的周期
            contract_list = df_contract[
                ["id", "project", "channel_code", "lot_code", "factory", "author_code"]].values.tolist()
        if not public_data.Token:  # 检查是否有Token
            get_token_to_public_data()
            if not public_data.Token:
                self.child_signal.emit("获取身份验证信息不成功")
                return
        if public_data.update_all:
            fax_tb = DF_Table("fax")
            doc_e_tb = DF_Table("doc_e")
            doc_f_tb = DF_Table("doc")
            fax_tb.clear_data()
            doc_f_tb.clear_data()
            doc_e_tb.clear_data()
        with ThreadPoolExecutor() as get_file_json_pool:
            futures = []
            for contract in contract_list:
                future = get_file_json_pool.submit(get_file_to_db, contract)
                futures.append(future)
            for future in as_completed(futures):
                msg = future.result()
                print(msg)
                self.child_signal.emit(msg)
        date_now = get_now_str()
        self.child_signal.emit( f"文函已完成更新:{date_now}")

